<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Verify_login extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->lang->load('breadcrumb', 'estonian');
        $this->load->model('User_model', 'UserModel', '', TRUE);
    }

    function index() {

        $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

        if ($this->form_validation->run() == FALSE) {
            //Field validation failed.  User redirected to login page
            $this->load->template('login');
        } else {
            if ($this->session->userdata('is_admin')) {
                redirect('admin', 'refresh');
            } else {
                redirect('home', 'refresh');
            }
            
        }
    }

    function check_database($password) {
        //Field validation succeeded.  Validate against database
        $email = $this->input->post('email');

        //query the database
        $result = $this->UserModel->login($email, $password);

        if ($result) {
            $sess_array = array();
            foreach ($result as $row) {
                $sess_array = array(
                'id' => $row->id,
                'email' => $row->email,
                'type' => $row->type,
                'logged_in' => TRUE,
                'is_admin' => ($row->type == 'superadmin' || $row->type == 'admin' ? TRUE : FALSE)
                );
                $this->session->set_userdata($sess_array);
            }
            return TRUE;
        } else {
            $this->form_validation->set_message('check_database', 'Vale email või parool.');
            return false;
        }
    }

}

?>